"""
SmartCity-LLM Trainer 主应用入口
FastAPI应用配置和启动
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
import structlog

from app.core.config import settings
from app.core.database import engine
from app.core.middleware import (
    RequestLoggingMiddleware,
    SecurityHeadersMiddleware,
    RateLimitMiddleware,
    ErrorHandlingMiddleware
)
from app.models import Base
from app.api.v1.router import api_router

# 配置结构化日志
structlog.configure(
    processors=[
        structlog.stdlib.filter_by_level,
        structlog.stdlib.add_logger_name,
        structlog.stdlib.add_log_level,
        structlog.stdlib.PositionalArgumentsFormatter(),
        structlog.processors.StackInfoRenderer(),
        structlog.processors.format_exc_info,
        structlog.processors.UnicodeDecoder(),
        structlog.processors.JSONRenderer()
    ],
    context_class=dict,
    logger_factory=structlog.stdlib.LoggerFactory(),
    wrapper_class=structlog.stdlib.BoundLogger,
    cache_logger_on_first_use=True,
)

logger = structlog.get_logger()

# 创建FastAPI应用实例
app = FastAPI(
    title=settings.PROJECT_NAME,
    description="IOT智慧城市LLM模型训练平台",
    version="1.0.0",
    openapi_url=f"{settings.API_V1_STR}/openapi.json" if settings.ENVIRONMENT != "production" else None,
    docs_url=f"{settings.API_V1_STR}/docs" if settings.ENVIRONMENT != "production" else None,
    redoc_url=f"{settings.API_V1_STR}/redoc" if settings.ENVIRONMENT != "production" else None,
)

# 中间件配置
# 注意：中间件按逆序执行，所以先添加的后执行

# 全局错误处理（最外层）
app.add_middleware(ErrorHandlingMiddleware)

# CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_HOSTS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 可信任主机中间件
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=settings.ALLOWED_HOSTS
)

# 安全头中间件
app.add_middleware(SecurityHeadersMiddleware)

# 速率限制中间件（仅生产环境）
if settings.ENVIRONMENT == "production":
    app.add_middleware(RateLimitMiddleware, max_requests=1000, window_seconds=60)

# 请求日志中间件（最内层）
app.add_middleware(RequestLoggingMiddleware)

# 注册API路由
app.include_router(api_router, prefix=settings.API_V1_STR)

@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logger.info("SmartCity-LLM Trainer 启动中...")
    
    # 创建数据库表(开发环境)
    if settings.ENVIRONMENT == "development":
        async with engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)
    
    logger.info("应用启动完成", environment=settings.ENVIRONMENT)

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logger.info("SmartCity-LLM Trainer 正在关闭...")

@app.get("/")
async def root():
    """根路径健康检查"""
    return {
        "message": "SmartCity-LLM Trainer API",
        "version": "1.0.0",
        "status": "running"
    }

@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True if settings.ENVIRONMENT == "development" else False,
        log_level="info"
    )